import 'package:dio/dio.dart';
import 'package:enjoy_plus_flutter_7/constants/index.dart';
import 'package:enjoy_plus_flutter_7/utils/PromptAction.dart';
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
import 'package:permission_handler/permission_handler.dart';

class LocationList extends StatefulWidget {
  const LocationList({super.key});

  @override
  State<LocationList> createState() => _LocationListState();
}

class _LocationListState extends State<LocationList> {
  String _address = '获取中...';
  @override
  void initState() {
    super.initState();

    // 向用户要位置授权
    _requestLocationPermission();
  }

  _requestLocationPermission() async {
    PermissionStatus status = await Permission.location.request(); // 请求位置权限
    if (status == PermissionStatus.granted) {
      print('获取位置权限成功');
      // 获取当前位置的经纬度
      _getLocation();
    } else {
      print('获取位置权限失败');
    }
  }

  _getLocation() async {
    Position p = await Geolocator.getCurrentPosition();
    print('${p.longitude} ${p.latitude}');
    _getAddress(p.longitude, p.latitude);
    _getNearbyCommunity(p.longitude, p.latitude);
  }

  _getAddress(double longitude, double latitude) async {
    Dio dio = Dio();
    var res = await dio.get(
        '${GlobalConstants.GD_BASE_URL}${HTTP_PATH.REVERSE_GEOCODING}',
        queryParameters: {
          'key': 'f08f53336e202e0308ae6cd050bf080e',
          'location': '$longitude,$latitude',
        });
    print(res);
    if (res.data['infocode'] == '10000') {
      setState(() {
        _address = res.data['regeocode']['formatted_address'];
      });
    } else {
      PromptAction.error('逆地理编码失败');
    }
  }

  // 获取周边小区
  // 获取周边小区

  List listx = [];
  _getNearbyCommunity(double longitude, double latitude) async {
    Dio dio = Dio();
    var res = await dio.get('${GlobalConstants.GD_BASE_URL}${HTTP_PATH.AROUND}',
        queryParameters: {
          'key': 'f08f53336e202e0308ae6cd050bf080e', // 标识使用者的身份信息
          // 'key': 'dd47b6b234842e9a25de0f90e46b243d', // 标识使用者的身份信息
          'location': '$longitude,$latitude', // 经纬度
          'keywords': '养生', // 搜索周边的什么
          'radius': 3000, // 搜索区域的半径  1000米
          'offset': 10 // 搜索结果的数量
        });
    print(res.data['pois']);
    if (res.data['infocode'] == '10000') {
      setState(() {
        listx = res.data['pois']; // 周边公交站   map
      });
    } else {
      // print('逆地理编码失败');
      PromptAction.error('周边搜索失败');
    }
  }

  List<Widget> getListChild() {
    return listx.map((item) {
      return Container(
          color: Colors.white,
          padding: const EdgeInsets.all(10),
          child: Row(
            children: [
              Expanded(child: Text(item["name"])),
              const Row(
                children: [
                  Icon(Icons.arrow_forward_ios, size: 16, color: Colors.black),
                ],
              )
            ],
          ));
    }).toList();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('选择社区'),
      ),
      body: ListView(
        padding: const EdgeInsets.all(10),
        children: [
          Row(
            children: [
              Text(
                '当前地址',
                style: TextStyle(color: Colors.grey),
              )
            ],
          ),
          const SizedBox(height: 10),
          Container(
            color: Colors.white,
            padding: const EdgeInsets.all(10),
            child: Row(
              children: [
                Expanded(child: Text(_address)),
                Row(
                  children: [
                    Icon(Icons.location_searching_outlined, color: Colors.blue),
                    SizedBox(width: 2),
                    Text(
                      '重新定位',
                      style: TextStyle(color: Colors.blue),
                    ),
                  ],
                )
              ],
            ),
          ),
          const SizedBox(height: 10),
          Row(
            children: [
              Text(
                '附近社区',
                style: TextStyle(color: Colors.grey),
              )
            ],
          ),
          const SizedBox(height: 10),
          ListView(
            shrinkWrap: true,
            physics: const NeverScrollableScrollPhysics(),
            children: getListChild(),
          )
        ],
      ),
    );
  }
}
